package com.nccs.arithmetic;

/**
 * @author xuzengsheng
 * @program: nssc-parent
 * @createTime 2021-09-14- 14:41:00
 * @description 冒泡排序 + 模板方法模式
 * 来源：https://blog.csdn.net/alan_liuyue/article/details/80740960
 */

public class BubbleSort extends AbstractSortHandler {

    public BubbleSort(String arithmeticName) {
        super(arithmeticName);
    }

    public static void main(String[] args) {
        new BubbleSort("冒泡排序").execute();
    }

    /**
     * 重写父类的sort方法
     *
     * @param arry
     * @return
     */
    @Override
    public void sort(int[] arry) {
        for (int i = 0; i < arry.length - 1; i++) {
            for (int j = 0; j < arry.length - 1 - i; j++) {
                if (arry[j] > arry[j + 1]) {
                    swap(arry, j, j + 1);
                }
            }
        }
    }

    //两个数据交换
    public static void swap(int[] arry, int val1, int val2) {
        //使用异或运算（不使用临时变量）交换两个变量的值
        arry[val1] ^= arry[val2];
        arry[val2] ^= arry[val1];
        arry[val1] ^= arry[val2];

        //使用临时变量交换两个变量的值
        //int temp = arry[val1];
        //arry[val1] = arry[val2];
        //arry[val2] = temp;
    }
}
